import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {postReq} from '@/utils/request'
import uri from '@/api/uri'
import store from '@/store'
//白名单
const whiteList = ['/login']

// 加载vue组件
const layoutModules = import.meta.glob('/src/views/**/*.vue')


//404
export const errorRoute: RouteRecordRaw = {
	path: '/:pathMatch(.*)',
	redirect:'/404'
}


const constantRoutes: RouteRecordRaw[] = [
	
	{
		path: '/404',
		component: () => import('../views/404.vue')
	},

	{
		path: '/login',
		component: () => import('../views/login/login.vue')
	},
	{
		path:'/publish/pipeline/',
		component:() =>{'../views/publish/pipeline/task-details.vue'}
	},

]

const asyncRoutes:RouteRecordRaw = {

	//redirect 重定向到home页面
	path: '/',
	component: () => import('../layout/index.vue'),
	redirect: '/home',
	children: [
		{
			path: '/home',
			name: 'Home',
			component: () => import('../views/home.vue'),
			meta: {
				title: '首页',
				affix: true
			}
		},



	]

}


export const router = createRouter({
	//历史模式，URL之前使用了一个#
	history: createWebHashHistory(),
	routes: constantRoutes
})


//路由加载之前
router.beforeEach(async (to, from, next)=>{
	//页面加载进度
	NProgress.start()
	if(store.userStore.token){
		//如果已经获取到了token，登录请求转发到请求首页
		if(to.path === '/login'){
			next('/home')
		}else if(!store.userStore.user.id){
			
			//如果不是登录请求，则需判断前端是否已经获取到了用户信息
			await store.userStore.getUserInfoAction()
	
			//从后端获取菜单信息
			const data = await getSystemMenuTree()

			//生成左侧菜单
			const menuPathList = generateMenuRoute(data)
	
			//路由
			const routeList = generateRoute(menuPathList,[])
			
			//添加到路由
			asyncRoutes.children?.push(...routeList)
			router.addRoute(asyncRoutes)
	
			//错误路由
			router.addRoute(errorRoute)
	
			//保存菜单信息
			store.routerStore.setMenuPaths(menuPathList)

			//保存路由信息
			store.routerStore.setRoutes(constantRoutes.concat(asyncRoutes))
			
			//放行
			next({ ...to, replace: true })
		}else{
			//已经获取到了用户信息，放行
			next()
		}	
		
	}else{
		//没有token
		if(whiteList.indexOf(to.path) > -1){
			//白名单放行
			next()
		}else{
			//本地浏览器不存在token且不是白名单的请求跳转到登录界面
			next('/login')
		}

	}
	
})

router.afterEach(()=>{
	NProgress.done()
})


const getSystemMenuTree=() =>{
	 return postReq(uri.getSystemMenu,{types:[0]}).then((res) => {
		return res.data
	 })
}


//生成左侧菜单
const generateMenuRoute=(menuList:any) => {
	//路由数组
	let menuRouteList:RouteRecordRaw[] = []

	menuList.forEach((menu:any) => {
	
		let component
		let path
		
		if(menu.children && menu.children.length > 0){
			component = () => import('@/layout/index.vue')
			path = '/p'+menu.id
		}else{
			if(menu.url.startsWith("/")){
				path =  menu.url
			}else{
				path = '/' + menu.url
			}
			component = layoutModules[`/src/views${path}.vue`]
		}

		const routeComponent: any = {
			path: path,
			name: path,
			component: component,
			children:[],
			meta:{
				title: menu.name,
				icon: menu.icon,
				id: '' + menu.id,
				cache: true,
				_blank: menu.openStyle === 1,
				breadcrumbs: []
			}
		}

		//如果有子菜单
		if(menu.children && menu.children.length > 0){
			routeComponent.children.push(...generateMenuRoute(menu.children))
		}
		
		menuRouteList.push(routeComponent);
	});

	return menuRouteList
}

const generateRoute=(menuRouteList:RouteRecordRaw[], breadcrumbList:string[]) =>{

	//路由数组
	let routeList:RouteRecordRaw[] = []
	menuRouteList.forEach((menuRoute:any) => {
	
		if(menuRoute.meta.title){
			//面包屑
			breadcrumbList.push(menuRoute.meta.title)
		}

		//如果有子菜单
		if(menuRoute.children && menuRoute.children.length > 0){
			routeList.push(...generateRoute(menuRoute.children,breadcrumbList))
		}else{
			//最后一层子菜单添加面包屑
			menuRoute.meta.breadcrumbs.push(...breadcrumbList)
			//路由
			routeList.push(menuRoute)
		}
		
		//将最后一级面包屑弹出，一个菜单栏下可能有多个子菜单
		breadcrumbList.pop()
	});

	return routeList

}
